﻿using AutoMapper;
using B.S.DataBase.Myproject.Helper;
using B.S.DataBase.MyProject.Domain.Infrastructures;
using B.S.DataBase.MyProject.Domain.PatientMobileDevice;
using B.S.DataBase.MyProject.Domain.wdx;
using B.S.DataBase.MyProject.Domain.wdx.ViewModels;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using Dm.util;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.Sign;
using SqlSugar;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.Sign
{
    public class GetSignListCommandHandler : IRequestHandler<GetSignListCommand, ApiPaging<View_SignList>>
    {
        private readonly SqlSugarContext sqlSugar;
        private readonly IMapper mapper;

        public GetSignListCommandHandler(SqlSugarContext sqlSugar, IMapper mapper)
        {
            this.sqlSugar = sqlSugar;
            this.mapper = mapper;
        }

        public async Task<ApiPaging<View_SignList>> Handle(GetSignListCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<View_SignList> result = new ApiPaging<View_SignList>();

            // 1. 先构建基础查询
            var query = sqlSugar.db.Queryable<ResidentFiles>()
                .InnerJoin<NCDSign>((file, sign) => file.ResidentFiles_Id == sign.Patient_Id);

            // 2. 添加多表查询条件
            if (request.ResidentFiles_Id != null && request.ResidentFiles_Id != 0)
            {
                query = query.Where((file, sign) => file.ResidentFiles_Id == request.ResidentFiles_Id);
            }
            if (request.Doctor_Name.IsNotNull())
            {
                query = query.Where((file, sign) => sign.Doctor.Contains(request.Doctor_Name));
            }
            if (request.Team != null && request.Team != 0)
            {
                query = query.Where((file, sign) => sign.Team == request.Team);
            }
            if (request.ResidentFiles_Name.IsNotNull())
            {
                query = query.Where((file, sign) => file.ResidentFiles_Name.Contains(request.ResidentFiles_Name));
            }
            if (request.CreateStartTime.IsNotNull() && request.CreateEndTime.IsNotNull())
            {
                var startDate = DateTime.Parse(request.CreateStartTime);
                var endDate = DateTime.Parse(request.CreateEndTime).AddDays(1).AddMilliseconds(-1);
                query = query.Where((file, sign) => sign.CreateTime >= startDate && sign.CreateTime <= endDate);
            }

            // 3. 执行投影和MergeTable
            var list = query.Select((file, sign) => new View_SignList
            {
                NCDSign_Id = sign.NCDSign_Id,
                Patient_Id = sign.Patient_Id,
                Team = sign.Team,
                Doctor = sign.Doctor,
                Sign_Status = sign.Sign_Status,
                Sign_StartTime = sign.Sign_StartTime.ToString(),
                Sign_EndTime = sign.Sign_EndTime.ToString(),
                ManageNCD = sign.ManageNCD,
                ManageLevel = sign.ManageLevel,
                ServicePack = sign.ServicePack,
                Proof = sign.Proof,
                CreateUser = sign.CreateUser,
                CreateTime = sign.CreateTime.ToString(),
                UpdateUser = sign.UpdateUser,
                UpdateTime = sign.UpdateTime,
                ResidentFiles_Id = file.ResidentFiles_Id,
                ResidentFiles_Name = file.ResidentFiles_Name,
                Sex = file.Sex == true ? "男" : "女",
                Age = file.Age,
                IdCard = file.IdCard,
                Phone = file.Phone,
                Birthday = file.Birthday,
                signDeviceBinds = SqlFunc.Subqueryable<SignDeviceBind>()
                    .Where(x => x.Patient_Id == sign.Patient_Id)
                    .ToList()
            }).MergeTable();

            // 4. 分页处理
            int TotalCount = await list.CountAsync();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);

            // 5. 获取分页数据
            result.list = await list.OrderByDescending(x => x.CreateTime)
                .ToPageListAsync(request.PageIndex, request.PageSize);

            // 6. 后处理
            foreach (var item in result.list)
            {
                item.TeamName = (await sqlSugar.db.Queryable<TeamInfo>()
                    .FirstAsync(x => x.TeamID == item.Team))?.TeamName;

                // 格式化日期
                item.Sign_StartTime = FormatDateTime(item.Sign_StartTime);
                item.Sign_EndTime = FormatDateTime(item.Sign_EndTime);
                item.CreateTime = FormatDateTime(item.CreateTime);
            }

            result.TotalCount = TotalCount;
            result.TotalPage = TotalPage;
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();

            return result;
        }

        private string FormatDateTime(string dateTimeStr)
        {
            if (DateTime.TryParse(dateTimeStr, out var dateTime))
            {
                return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            return "--";
        }
    }
}